<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>注册</h2>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="registerForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="公司名称" prop="company">
          <el-input
            v-model="registerForm.company"
            placeholder="请输入公司名称"
          />
        </el-form-item>
        
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input
            v-model="registerForm.creditCode"
            placeholder="请输入统一社会信用代码"
          />
        </el-form-item>
        
        <el-form-item label="公司类型" prop="companyType">
          <el-select
            v-model="registerForm.companyType"
            placeholder="请选择公司类型"
            style="width: 100%"
          >
            <el-option label="国有企业" :value="1" />
            <el-option label="民营企业" :value="2" />
            <el-option label="外资企业" :value="3" />
            <el-option label="合资企业" :value="4" />
            <el-option label="其他" :value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属行业" prop="industry">
          <el-select
            v-model="registerForm.industry"
            placeholder="请选择所属行业"
            style="width: 100%"
          >
            <el-option label="互联网/IT" :value="1" />
            <el-option label="金融" :value="2" />
            <el-option label="制造业" :value="3" />
            <el-option label="服务业" :value="4" />
            <el-option label="其他" :value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="联系人" prop="contactPerson">
          <el-input
            v-model="registerForm.contactPerson"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>
        
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input
            v-model="registerForm.contactPhone"
            placeholder="请输入联系电话"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="register-button"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
        
        <div class="form-footer">
          <router-link to="/login">
            已有账号？立即登录
          </router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { register } from '../api/user'
import { initSecureKeys } from '../api/secure'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  company: '西南交通大学',
  creditCode: '12100000450752090P',
  companyType: 1,
  industry: 1,
  contactPerson: '曹行阳',
  contactPhone: '17684214564'
})

const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入公司名称', trigger: 'blur' }
  ],
  creditCode: [
    { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
    { pattern: /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/, message: '请输入正确的统一社会信用代码', trigger: 'blur' }
  ],
  companyType: [
    { required: true, message: '请选择公司类型', trigger: 'change' }
  ],
  industry: [
    { required: true, message: '请选择所属行业', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

const handleRegister = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const response = await register({
      username: registerForm.value.username,
      password: registerForm.value.password,
      company: registerForm.value.company,
      creditCode: registerForm.value.creditCode,
      companyType: registerForm.value.companyType,
      industry: registerForm.value.industry,
      contactPerson: registerForm.value.contactPerson,
      contactPhone: registerForm.value.contactPhone
    })
    
    // 注册成功后初始化密钥
    try {
      if (response) {
        // 保存 uuid 到 localStorage
        localStorage.setItem('userId', response.id)
        localStorage.setItem('user_uuid', response.userId)
        await initSecureKeys(response.userId, registerForm.value.password)
        ElMessage.success('密钥初始化成功')
      } else {
        throw new Error('注册响应数据无效')
      }
    } catch (error: any) {
      console.error('密钥初始化失败:', error)
      ElMessage.warning('密钥初始化失败，请稍后重试')
    }
    
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  padding: 40px 0;
  
  .register-card {
    width: 600px;
    
    .card-header {
      text-align: center;
      
      h2 {
        margin: 0;
        color: #303133;
      }
    }
    
    .register-button {
      width: 100%;
    }
    
    .form-footer {
      text-align: center;
      margin-top: 20px;
      
      a {
        color: #409EFF;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style> 